<?php
/**
 * 处理推荐商品, 返回商品的 product_tag_ids
 * Author: lyun
 * Date: 2018/7/26
 * Created by Panxsoft.
 */

namespace App\Services\Repositories\Product;


use App\Http\Controllers\ApiController;
use App\Http\Requests\Wechat\RecommendProductIndexRequest as RecommendProductRequest;
use App\Http\Requests\App\RecommendProductIndexRequest;
use App\Models\Panx\ProductTag;
use App\Models\Panx\SkinDetector;
use App\Models\Panx\Tags\SkinDetectionItem;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;

/**
 * @deprecated - WIP 废弃，不要依赖 request
 *
 * Class DeprecatedRecommendProductRepository
 *
 * @package App\Services\Repositories\Product
 */
class DeprecatedRecommendProductRepository extends ApiController
{
    /**
     * @param Request|RecommendProductIndexRequest|RecommendProductRequest $request
     * @return array
     * @throws \Exception
     */
    public function getTagIds(Request $request): array
    {
        if ((int)$request->skin_detector_id === SkinDetector::ID_WAX) {
            return $this->getProductTagIdsByWax($request);
        } else if ((int)$request->skin_detector_id === SkinDetector::ID_HM) {
            return $this->getProductTagIdsByHm($request);
        } else {
            return [];
        }
    }

    /**
     * @param Request|RecommendProductIndexRequest|RecommendProductRequest $request
     * @return mixed
     * @throws \Exception
     */
    private function getProductTagIdsByWax(Request $request): array
    {
        /** @var SkinDetectionItem $skin_detection_item */
        $skin_detection_item = SkinDetectionItem::where('skin_detector_id', $request->skin_detector_id)
            ->where('item_id', $request->wax_sid)
            ->first();
        $this->checkItemExist($skin_detection_item, trans('admin.skin_detection_item'));

        $product_tag_ids = $skin_detection_item->productTags
            ->pluck('id')
            ->all();

        return $product_tag_ids;
    }

    /**
     * @param Request|RecommendProductIndexRequest|RecommendProductRequest $request
     * @return array
     */
    private function getProductTagIdsByHm(Request $request): array
    {
        $skin_detector_id = $request->skin_detector_id;

        $product_tag_ids =  (new ProductTag)
            ->whereHas('skinDetectionItems', function(Builder $query) use($skin_detector_id) {
                return $query->where('skin_detector_id', $skin_detector_id);
            })
            ->pluck('id')
            ->all();

        return $product_tag_ids;
    }
}



